﻿using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Caliburn.Micro;
using Microsoft.Practices.Unity;
using NMortgage.UI.ViewModels;

namespace NMortgage.UI
{
    [ExcludeFromCodeCoverage] // unable to test this, this is required by Caliburn
    public class AppBootstrapper : Bootstrapper<MainViewModel>
    {
        private IUnityContainer _container;

        protected override System.Collections.Generic.IEnumerable<System.Reflection.Assembly> SelectAssemblies()
        {
            yield return Assembly.GetExecutingAssembly();
        }
        protected override void Configure()
        {
            _container = new UnityContainer();
            _container.RegisterType<IWindowManager, WindowManager>(new ContainerControlledLifetimeManager());
            _container.RegisterType<IEventAggregator, EventAggregator>(new ContainerControlledLifetimeManager());
        }
        protected override System.Collections.Generic.IEnumerable<object> GetAllInstances(System.Type service)
        {
            return _container.ResolveAll(service);
        }
        protected override object GetInstance(System.Type service, string key)
        {
            if (string.IsNullOrEmpty(key))
                return _container.Resolve(service);

            var type = Type.GetType(key);

            if(type != null)
                return _container.Resolve(type);

            return _container.Resolve(service, key);
        }
        protected override void BuildUp(object instance)
        {
            _container.BuildUp(instance);
        }
    }
}